package com.heima.search.listener;

import com.alibaba.fastjson.JSON;
import com.heima.common.constants.ArticleConstants;
import com.heima.common.constants.WmNewsMessageConstants;
import com.heima.model.search.vos.SearchArticleVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

@Component
@Slf4j
@RequiredArgsConstructor
public class SyncArticleListener {


    private final RestHighLevelClient restHighLevelClient;

    /**
     * 监听es索引创建消息
     * @param  vo
     */
    @RabbitListener( bindings = @QueueBinding(
            value = @Queue(name = ArticleConstants.ARTICLE_ES_SYNC_TOPIC),
            exchange = @Exchange(name = ArticleConstants.ARTICLE_ES_SYNC_EXCHANGE,type = ExchangeTypes.DIRECT)
    ))
    public void onMessage(SearchArticleVo vo) throws IOException {
        if (vo != null) {
            log.info("创建es索引库，ID: {}", vo.getId());
            // 创建es索引
            IndexRequest indexRequest = new IndexRequest("app_info_article");
            indexRequest.id(vo.getId().toString());
            // 使用JSON.toJSONString来确保vo被正确序列化为JSON格式
            indexRequest.source(JSON.toJSONString(vo), XContentType.JSON);
            try {
                restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
            } catch (IOException e) {
                log.error("远程异步索引创建失败，ID: {}, Error: {}", vo.getId(), e.getMessage(), e);
                // 直接抛出原始IOException或者包装成自定义异常
                throw e;
            }
        }
    }

}












